import URL from '@/config/url-config.js';

function request(config, anon = true) {
	let promise = new Promise(function(resolve, reject) {
		if (anon) {
			let sign = uni.getStorageSync('sign')
			if (!sign) {
				reject({
					msg: "sign is null",
					code: 500
				});
				return
			}
		}
		uni.request(config).then(responses => {
			// 异常
			if (responses[0]) {
				reject({
					msg: "网络超时"
				});
			} else {
				// 可增加登录超时 code:401 校验
				resolve(responses[1]);
			}
		}).catch(error => {
			reject(error);
		})
	})
	return promise;
}

function authSign(params, callback) {
	authLoad(() => {
		if (params && params.sign) {
			uni.setStorageSync('sign', params.sign)
		}
		var sign = uni.getStorageSync('sign')
		if (!sign) {
			//跳转到授权页
			toWxauth();
			return
		}
		if (callback) {
			callback()
		}
	})
}

function authLoad(callback){
	var interval = setInterval(() => {
		var turn = uni.getStorageSync('loadOver')
		if (turn) {
			callback()
			clearInterval(interval)
		}
	
	}, 100)
}

function toWxauth(){
	//跳转到授权页
	let rnd = new Date().getTime()
	let redirectUriParam = 'rnd=' + rnd//自定义传参
	let pages = getCurrentPages();
	let page = pages[pages.length - 1];
	let fullPath = page['__page__'].fullPath
	if (fullPath.indexOf('?') == -1) {
		fullPath = fullPath + "?" + redirectUriParam
	} else {
		fullPath = fullPath + "&" + redirectUriParam
	}
	let redirect_uri = URL.redirectDomain + fullPath
	let href_url = `${URL.wxauth}?success_page=${encodeURIComponent(redirect_uri)}`//success_page为服务端回调链接地址
	window.location.href = href_url
}

module.exports = {
	request: request,
	authSign: authSign
}
